/**
 * 筛选指标设置
 */
import React,{PropTypes,Component,PureComponent}  from 'react';
import {Select ,
	Button ,
	Tree ,
	Modal,
	Form,
	Input,
	message,
	TreeSelect,
	DatePicker,
	Row,
	Col ,
	Card,
	} from 'antd';
import { connect } from 'dva';
import {countRangeList,establishLife,fundScale}  from '../../../utils/dataConfig';
import { treeKpi } from './treeKpi';
import moment from 'moment';

import style from './schemesetup.less';

const Option = Select.Option;
const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const dateFormat = 'YYYY/MM/DD';

class RangeInput extends React.Component {
	constructor(props) {
			super(props);
			const value = this.props.value || {};
			this.state = {
				minnum: '',
				maxnum: '',
			};
		}
		componentWillMount(){
			console.log("plansssssssssss,componentWillMount",this.props);
			const value = this.props.value;
			this.setState({
				minnum: value.minnum,
				maxnum: value.maxnum,
			})
		}
		
		componentWillReceiveProps(nextProps) {
			// const { schemeId } = this.props;
			console.log("plansssssssssss,nextProps",nextProps,);
				// if(schemeId !== nextProps.schemeId){
				// 	this.setState({
				// 		minnum:'',
				// 		maxnum:''
				// 	});
				// }
				if ('value' in nextProps) {
					const value = nextProps.value;
					this.setState({
						minnum:value.minnum,
						maxnum:value.maxnum
					});
				}
			}

	handleminnumChange = (e) => {
		const minnum = e.target.value;
		console.log("llprops",this.props);
		if(_.isNumber(minnum)){
			return;
		}
		if (!('value' in this.props)) {
			this.setState({ minnum: minnum});
		}
		this.triggerChange({ minnum });
	}

	handlemaxnumChange = (e) => {
		const maxnum = e.target.value;
		if(_.isNumber(maxnum)){
			return;
		}
		if (!('value' in this.props)) {
			this.setState({ maxnum:maxnum });
		}
		this.triggerChange({ maxnum });
	}

	triggerChange = (changedValue) => {
		const onChange = this.props.onChange;
		if (onChange) {
			onChange(Object.assign({}, this.state, changedValue));
		}
	}
	render() {
		const state = this.state;
		console.log("9090",state);
		return (
			<span>
				<Input
					type="number"
					value={state.minnum}
					onChange={this.handleminnumChange}
					style={{ width: 70 }}
					addonAfter="%"
				/>&nbsp;
				<span>至</span>
				&nbsp;
				<Input
					type="number"
					value={state.maxnum}
					onChange={this.handlemaxnumChange}
					style={{ width: 70 }}
					addonAfter="%"
				/>
			</span>
		);
	}
}

// RangeInput.propTypes = {
// }

// export default connect(({fundpool})=>({fundpool}))(RangeInput)


const FORM_ITEM_LAYOUT_RANGE = {
	labelCol:{
		xl:{
			span:5,
		},
		lg:{
			span:5,
		},
		md: {
			span: 7,
		},
		sm: {
			span: 7,
		},
	},
	wrapperCol:{
		xl:{
			span:15,
		},
		lg:{
			span:15,
		},
		md: {
			span: 13,
		},
		sm: {
			span: 13,
		},
	}
}
const FORM_ITEM_LAYOUT = {
	labelCol: {
		xl:{
			span:5,
		},
		lg:{
			span:5,
		},
		md: {
			span: 5,
		},
		sm: {
			span: 5,
		},
	},
	wrapperCol: {
		xl:{
			span:11
		},
		lg:{
			span:11
		},
		md:{
			span:11
		},
		sm: {
			span: 12,
		},
		xs: {
			span: 13,
		},
	},
};
const SchemeSetup =({
	dispatch,
	fundpool,
	form: {
		getFieldDecorator,
		validateFields,
		getFieldsValue, 
		resetFields,
		setFieldsValue,
		getFieldValue,
		getFieldProps
 }
})=>{
	const { 
		kpiNameList,
		statusS,
		investStrategy,
		countRangeValue,
		selectKpiList,
		timeRange,
		beginDate,
		endDate,
		benchmark,
		establish,
		fundS,
		invest,
		schemeId
	} = fundpool;
		console.log("SchemeSetup>>>",fundpool);
	function handleSubmit  (e)  {
		e.preventDefault();
		validateFields((err, fieldsValue) => {
			if (err) {
				return;
			}
			const attrArr = [];
			console.log('fieldsValue>>>>fieldsValue',fieldsValue,timeRange)	
			for(var i in fieldsValue) {
				console.log('fieldsValue>i',i,'--',fieldsValue[i])
				var attrObj = {};
				attrObj.kpiName = i ;
				if(i == "investStrategy" || "establishAge" || "status" || "fundScale"){
					attrObj.value = fieldsValue[i];
					// countRange
					attrObj.kpiType = "attr";
					if(attrObj.value == ""){
						for(let key in attrObj){
							delete attrObj[key];
						}
					}
				}

				if(i == "annualYieldRate" || i == "alpha" || i == "sharpeRatio" ||
					i == "treynorRatio" || i == "informationRatio" || i == "sortinoRatio" || i == "m2" || i == "calmarRatio" || i == "var" || i == "volatility" || i == "cte" || i == "te" || i == "beta" || i == "maxDrawdown" ){
					attrObj.kpiType = "kpi";
					if(_.isEmpty(fieldsValue[i].minnum) && _.isEmpty(fieldsValue[i].maxnum)){
						//最大值最小值都为空
						for(let key in attrObj){
							delete attrObj[key];
						}
					}else if(!_.isEmpty(fieldsValue[i].minnum) && !_.isEmpty(fieldsValue[i].maxnum)){
						//最大值最小值都不为空
						const maxNum = fieldsValue[i].maxnum / 100;
						const minNum = fieldsValue[i].minnum / 100;
						attrObj.value=minNum;
						attrObj.maxValue=maxNum;
					}else if(_.isEmpty(fieldsValue[i].minnum)){
						//最小值为空,最大值不为空
						const maxNum = fieldsValue[i].maxnum / 100;
						attrObj.maxValue=maxNum;
						delete attrObj.value;
					}else if(_.isEmpty(fieldsValue[i].maxnum)){
						//最小值不为空,最大值为空
						const minNum = fieldsValue[i].minnum / 100;
						attrObj.value=minNum;
						delete attrObj.maxnum;
					}
				}
				console.log('fieldsValue>attrObj',attrObj)
				
				attrArr.push(attrObj);
			}
			// attrArr.map((item,i)=>{
	 //      if(item.kpiName == "countRange" || item.kpiName == "investStrategy" || item.kpiName == "establishAge" || item.kpiName == "status" || item.kpiName == "fundScale"){
	 //        item["kpiType"]="attr";
					
	 //      }else{
	 //        item["kpiType"]="kpi"
	 //      }
	 //    })
	 var SendArr = []
			for(let j=0;j<attrArr.length;j++){
				if(!_.isEmpty(attrArr[j])){
					SendArr.push(attrArr[j])
				}
			}
			if(benchmark == ''){
				message.warning("请选择基准!");
				return;
			}
			if(timeRange == '7'){
				if(_.isEmpty(beginDate) && _.isEmpty(endDate)){
					message.warning("请选择时间!");
					return;
				}else{
					dispatch({
	         	type: 'fundpool/changeRouter',
	         	payload: {
	         		schemeId:schemeId,
	            countRange: '7',
	            benchId:benchmark,
	            beginDate: beginDate,
	            endDate: endDate
	          }
	       	})
				}
			}else{
				dispatch({
	         	type: 'fundpool/changeRouter',
	         	payload: {
	         		schemeId:schemeId,
	            countRange: timeRange,
	          	benchId:benchmark,
	          }
	       	})
				// SendArr.push({
				// 	kpiName : 'countRange',
				// 	value : parseInt(timeRange),
				// 	kpiType : "attr",
				// })
			}
			
			console.log('fieldsValue>attrArr',attrArr,SendArr)
			dispatch({
				type:"fundpool/schemeSelect",
				payload:SendArr
			})
		})		
	}
	//清空条件
	function handleReset(){
		resetFields();
		dispatch({
			type: `fundpool/setState`,
			payload: {
				benchmark:'',
				beginDate:'',
				endDate:''
			}
		})
	}
	//成立年限
	function handleestablishSelect(v){
		dispatch({
			type: `fundpool/setState`,
			payload: {
				establish:v
			}
		})
	}
	//基金规模
	function handlefundScaleSelect(v){
		dispatch({
			type: `fundpool/setState`,
			payload: {
				fundS:v
			}
		})
	}
	//投资策略
	function handleinvestStrategySelect (v) {
		dispatch({
			type: `fundpool/setState`,
			payload: {
				invest:v
			}
		})
	}
	//状态
	function handlestatusSSelect(v){
		dispatch({
			type: `fundpool/setState`,
			payload: {
				statusSs:v
			}
		})
	}

	function getFields() {
		const children = [];
		selectKpiList.map((item,i)=>{
			if(item.type == 'range'){
				children.push(
					<Col span={6} key={i} style={{paddingLeft:9}}>
						<FormItem label={`${item.title}`}
							{...FORM_ITEM_LAYOUT_RANGE}
						>
							{getFieldDecorator(`${item.key}`, {
								initialValue: {minnum:'',maxnum:''},
							})(<RangeInput/>)}
						</FormItem>
					</Col>
				);
			}
			if(item.type == 'choice' && item.key == 'establishAge'){
				children.push(
				 <Col span={6} key={item.key} >
						<FormItem label={`${item.title}`}
							{...FORM_ITEM_LAYOUT}
						>
						{getFieldDecorator(`${item.key}`,{
							 initialValue: establish,
						},)(
							<Select onSelect={handleestablishSelect}>
							 {
								 establishLife.map((item,index) => <Option value={item.value} key={item.value} defaultValue={item.value}>{item.name}</Option> )
							 }
						 </Select>
						)}
						</FormItem>
					</Col>
				)
			}
			if(item.type == 'choice' && item.key == 'fundScale'){
				children.push(
				 <Col span={6} key={item.key} >
						<FormItem label={`${item.title}`}
							{...FORM_ITEM_LAYOUT}
							>
						{getFieldDecorator(`${item.key}`,{
							 initialValue: fundS,
						},)(
							<Select onSelect={handlefundScaleSelect}>
							 {
								 fundScale.map((item,index) => <Option value={item.value} key={item.value}>{item.name}</Option> )
							 }
						 </Select>
						)}
						</FormItem>
					</Col>
				)
			}
			if(item.type == 'choice' && item.key == 'investStrategy'){
				children.push(
				 <Col span={6} key={item.key} >
						<FormItem label={`${item.title}`}
							{...FORM_ITEM_LAYOUT}
							>
						{getFieldDecorator(`${item.key}`,{
							 initialValue: invest,
						},)(
							<Select onSelect={handleinvestStrategySelect}>
							 {
								 investStrategy.map((item,index) => <Option value={item.value} key={item.value}>{item.name}</Option> )
							 }
						 </Select>
						)}
						</FormItem>
					</Col>
				)
			}
			if(item.type == 'choice' && item.key == 'status'){
				children.push(
				 <Col span={6} key={item.key} >
						<FormItem label={`${item.title}`}
							{...FORM_ITEM_LAYOUT}
							>
						{getFieldDecorator(`${item.key}`,{
							 initialValue: "",
						},)(
							<Select onSelect={handlestatusSSelect}>
							 {
								 statusS.map((item,index) => <Option value={item.value} key={item.value}>{item.name}</Option> )
							 }
						 </Select>
						)}
						</FormItem>
					</Col>
				)
			}
		})
		return children;

	}
	const TimeRangeSelect=({data,value})=>{
		const myProps={
			defaultValue:data&&data.length?data[0].name:'',
			data,
			value,
			onSelect:(v)=> {
			dispatch({
				type: `fundpool/setState`,
				payload: {
					timeRange:v,
				}
			})
			if(v !== '7'){
				dispatch({
					type: `fundpool/setState`,
					payload: {
						beginDate:'',
						endDate:''
					}
				})
			}
		},
	}
	return (
		<Select {...myProps}>
			{
				data.map((item,i)=><Option value={item.value} key={i}>{item.name}</Option>)
			}
		</Select>
	)
}

const DateRangePicker=({beginDate,endDate})=>{
	const myProps={
		onChange:(v)=> {
			if(v.length){
				dispatch({
					type: `fundpool/setState`,
					payload: {
						beginDate:v[0].format("YYYYMMDD"),
						endDate:v[1].format("YYYYMMDD")
					}
				})
			}
		},
		//style:{width:200}
		style:{width:212}
	}
	if(beginDate){
		myProps.defaultValue=[moment(beginDate), moment(endDate)]
	}

	return (
		<RangePicker
			{...myProps}
		/>
	)
}

	return(
		<div>
			<Form onSubmit={handleSubmit} className={style.selectForm}>
				<Row gutter={16} style={{margin:0}} type="flex" justify="start">
					<Col span={6} >
						<FormItem
							label="统计区间"
							{...FORM_ITEM_LAYOUT}
							>
							<TimeRangeSelect
								data={countRangeList}
								value={timeRange&&countRangeList[0].value!=''?countRangeList.find(item=>item.value==timeRange).name:''}
							/>
						</FormItem>
					</Col>
					{
						timeRange==='7'?<Col span={6} >
							<FormItem
								label="时间选择"
								{...FORM_ITEM_LAYOUT}
							>
								<DateRangePicker
									beginDate={beginDate}
									endDate={endDate}
								/>
							</FormItem>
						</Col>:null
					}
					{getFields()}
				</Row>
				
					<Row>
						<FormItem
							wrapperCol={{
								xl: { span: 16, offset: 3 },
								lg: { span: 16, offset: 3 },
								xs: { span: 8, offset: 3 },
								sm: { span: 6, offset: 3 },
							}}
						>
							<Row type="flex" justify="center" align="top">
								<Col >
									<Button type="primary" htmlType="submit" size="large" >提交</Button>
								</Col>
								<Col >
										<Button type="primary" size="large" onClick={handleReset}>清空条件</Button>
								</Col>
							</Row>
						</FormItem>
					</Row>
			</Form>
		</div>
	)
}

SchemeSetup.propTypes = {}

export default connect(({fundpool})=>({fundpool}))(Form.create()(SchemeSetup))


